<template>
  <div class="connContent">
    <el-col class="title" style="height: 40px;flex: 0;">
      <div class="left"></div>
      <div class="right">
        <el-button  type="primary" @click="updateDSConnect">保存</el-button>
        <el-button bg text type="info" @click="emits('cancel')">取消</el-button>
      </div>
    </el-col>
    <!-- tab区 -->
    <!--    <el-col class="topbar">-->
    <div class="tabs_style">
      <el-tabs v-model="activeIndex" :before-leave="handleSelect" type="border-card">
        <el-tab-pane label="基本信息" name="0"></el-tab-pane>
        <el-tab-pane label="表信息" name="1"></el-tab-pane>
        <el-tab-pane label="视图信息" name="2"></el-tab-pane>
      </el-tabs>
    </div>

    <!--    </el-col>-->
    <!-- 基本信息区 -->
    <el-col v-if="activeIndex == '0'" class="formArea ">
      <el-form
          ref="ruleFormRef"
          :model="dsInfo"
          :rules="rules"
          label-position="right"
          label-width="100px"
          style="max-width: 460px"
      >
        <el-form-item label="数据库名称" prop="dsName" required>
          <el-input v-model="dsInfo.dsName"/>
        </el-form-item>
        <el-form-item label="数据库类型" prop="dsType" required>
          <el-select
              v-model="dsInfo.dsType"
              class="m-2 dsTypeSelect"
              placeholder="请选择数据库类型"
          >
            <el-option label="MYSQL" value="MYSQL"/>
            <el-option label="ORACLE" value="ORACLE"/>
          </el-select>
          <!-- <el-input v-model="dsInfo.dsType" /> -->
        </el-form-item>
        <el-form-item label="数据库地址" prop="dsAddr" required>
          <el-input v-model="dsInfo.dsAddr"/>
        </el-form-item>
        <el-form-item label="端口" prop="dsPort" required>
          <el-input v-model="dsInfo.dsPort"/>
        </el-form-item>
        <el-form-item label="数据库名" prop="dsSchema" required>
          <el-input v-model="dsInfo.dsSchema"/>
        </el-form-item>
        <el-form-item label="用户名" prop="userName" required>
          <el-input v-model="dsInfo.userName"/>
        </el-form-item>
        <el-form-item label="密码" prop="userPass" required>
          <el-input v-model="dsInfo.userPass" show-password/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkConnect(ruleFormRef)">测试连接</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col v-if="activeIndex != '0'" class="table_container ">
      <!-- 标题 -->
      <el-col class="title upBar">
        <div class="left">
          <span style="font-size:14px;">{{ tempValue }}名称/注释</span>
          <el-input v-model="tempValueFilter" class="input"/>
        </div>
      </el-col>
      <!-- 表信息 -->
      <el-table
          v-if="activeIndex != '0'"
          :data="tableDataFilter"
          :default-sort="{ prop: 'date', order: 'descending' }"
          class="table"
      >
        <el-table-column
            :label="tempValue + '名称'"
            prop="tableName"
            sortable
        />
        <el-table-column
            :label="tempValue + '注释'"
            prop="tableComment"
            sortable
        />
      </el-table>
      <!-- 底部分页 -->
      <el-col class="table_bottom_pagination">
        <el-pagination
            v-model="pageConfig"
            :default-page-size="20"
            :page-sizes="[20, 50, 100]"
            :total="pageConfig.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            next-text="下一页"
            prev-text="上一页"
            total-text="总数"
            @size-change="onPageSizeChange"
            @current-change="onPageChange"
            @prev-click="onPageChange"
            @next-click="onPageChange"
        />
      </el-col>
    </el-col>

    <!-- 重命名弹窗 -->
    <el-dialog v-model="renameDia" draggable title="重命名" width="300">
      <el-input v-model="rename"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDia = false">取消</el-button>
          <el-button
              type="primary"
              @click="renameDia = false;              rename = dsInfo.dsName"
          >确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, reactive, ref, toRefs, watch} from "vue";
import {getDataConnectInfo, getDSTableViewInfo, saveDSConnectConfig, testDataConnect} from '@/services/dataConnection'
import {ElMessage} from "element-plus";

const props = defineProps({
  dsId: String,
  groupId: String
});
const ruleFormRef = ref()

const data = reactive({
  tableData: [],
  activeIndex: "0",
  tempValueFilter: "",
});
const {tableData, activeIndex, tempValueFilter} = toRefs(data);

const dsInfo = ref({
  dsNO: "",
  dsAddr: "",
  dsPort: "",
  userName: "",
  userPass: "",
  dsName: "",
  dsType: "",
  dsSchema: "",
});
const rules = reactive({
  dsName: [{required: true, message: '请输入数据库名称', trigger: 'change',}],
  dsAddr: [{required: true, message: '请输入数据库地址', trigger: 'change',}],
  dsPort: [{required: true, message: '请输入端口', trigger: 'change',}],
  userName: [{required: true, message: '请输入用户名', trigger: 'change',}],
  userPass: [{required: true, message: '请输入密码', trigger: 'change',}],
  dsType: [{required: true, message: '请选择数据库类型', trigger: 'change',}],
  dsSchema: [{required: true, message: '请输入数据库名', trigger: 'change',}],
})

const pageConfig = reactive({
      'page-size': 20,
      'current-page': 1,
      total: 0,
    }
)

const tableDataFilter = computed(() => {
  if (tableData.value.length < 1) return;
  const list = tableData.value;
  return list.filter(
      (item) => item.tableName.indexOf(tempValueFilter.value) != -1
  );
});
/*//监听页数变化，重新请求table
watch(pageConfig, () => {
  console.log('监测生效')
  selectTablesInfo()
})*/

// 名称或注释
const tempValue = computed(() => {
  return activeIndex.value == "1" ? "表" : "视图";
});
// const dsNO = inject("dsNO");
const dsNo = ref('')
watch(props, (newProps) => {
  const {dsId} = newProps
  if (!dsId) {
    ruleFormRef.value.resetFields()
    dsInfo.value.dsNO = ''
  } else {
    selectDSConnectInfo(dsId);
  }
  activeIndex.value = '0';
})
//tab跳转
const handleSelect = async (activeName, oldActiveName) => {
  let pass = false
  if (oldActiveName == '0') {
    await ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        activeIndex.value = activeName;
        selectTablesInfo()
        pass = true
      }
    })
  } else {
    pass = true
  }
  return pass
};

const emits = defineEmits(["cancel", 'treeFresh']);
const renameDia = ref(false); // 重命名弹窗
const rename = ref("");

async function updateDSConnect() {
  const data = dsInfo.value
  data.dsIP = data.dsAddr
  data.password = data.userPass
  data.groupCode = props.groupId
  console.log(data)
  const res = await saveDSConnectConfig(data)
  if (res.respStatus) {
    ElMessage({
      message: res.respMessage,
      type: "success",
    });
    emits('treeFresh')
    ruleFormRef.value.resetFields()
  } else {
    ElMessage({
      message: res.respMessage,
      type: "error",
    });
  }
}

async function selectDSConnectInfo(dsNO) {
  const res = await getDataConnectInfo({
    dsNO,
  });

  if (!res?.respStatus)
    return ElMessage({
      message: "查询数据源连接失败：" + res?.respMessage,
      type: "error",
    });
  dsInfo.value = res?.respData || {}
  // rename.value = dsInfo.dsName;
}


//测试连接
async function checkConnect(formEl) {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('dsInfo', dsInfo.value)
      let data = dsInfo.value
      data.dsIP = data.dsAddr

      const {respStatus, respMessage} = await testDataConnect(data);
      console.log(respStatus, respMessage)
      if (!respStatus)
        return ElMessage({
          message: "连接失败：" + respMessage,
          type: "error",
        });
      return ElMessage({
        message: "连接成功",
        type: "success",
      })
    } else {
      console.log('error submit!', fields)
    }
  })

}

//表信息、视图信息
async function selectTablesInfo() {

  /*  await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        let data = dsInfo.value
        data.dsIP = data.dsAddr
        data.operType = activeIndex.value == '1' ? 'TABLE' : 'VIEW'
        const pageInfo = pageConfig
        data.pageLimit = {
          pageIndex: pageInfo["current-page"],
          pageRow: pageInfo["page-size"]
        }

      }
    })*/

  let data = dsInfo.value
  data.dsIP = data.dsAddr
  data.operType = activeIndex.value == '1' ? 'TABLE' : 'VIEW'
  const pageInfo = pageConfig
  data.pageLimit = {
    pageIndex: pageInfo["current-page"],
    pageRow: pageInfo["page-size"]
  }


  const res = await getDSTableViewInfo(data)
  if (res?.respStatus) {
    tableData.value = res.respData.dataList;
    pageInfo.total = res.respData.pageLimit.totalCount
    pageInfo["page-size"] = res?.respData?.pageLimit?.pageRow || 20
    pageInfo["current-page"] = res?.respStatus?.pageLimit?.pageIndex || 1
  } else {
    ElMessage({
      message: "查询失败：" + res.respMessage,
      type: "error",
    })
  }

}

//页码信息更改
function onPageChange(pageIndex) {
  pageConfig["current-page"] = pageIndex
  selectTablesInfo()
}

//更改页面行数信息
function onPageSizeChange(pageRow) {
  pageConfig["page-size"] = pageRow
  selectTablesInfo()
}

function checkEmpty(obj) {
  for (let key in obj) {
    if (!obj[key]) return false;
  }
  return true;
}

function showMessage(message, type) {
  ElMessage({message, type});
}
</script>

<style lang="scss" scoped>
.connContent {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: scroll;

:deep(.el-tabs .el-tabs__content){
  padding: 0;
}
  .table_container {
    flex: 1;

    .table_bottom_pagination {
      padding: 5px 0;
    }
  }

  .topbar .el-menu {
    background-color: #f7f7f7;
  }

  .formArea {
    flex: 0;;
    padding-top: 15px;

    .dsTypeSelect {
      width: 500px;
    }
  }

  .left {
    padding: 10px;
    font-size: 20px;
  }
.right{
  margin: 5px;
}
  .icon {
    cursor: pointer;
    color: #808080;
    padding: 5px;

    &:hover {
      color: skyblue;
    }
  }

  .table {
    height: calc(100% - 52px - 32px);

    //height: calc(100% - 73px - 42px);
    //padding-bottom: 60px;
  }

  .upBar,
  .downBar {
    background-color: #f7f7f7;
    border-top: solid 1px #dedede;
    width: 100%;

    .input {
      width: 200px;
      margin-left: 10px;
    }
  }

  .downBar {
    position: fixed;
    bottom: 0px;
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;
    }
  }
}
</style>